package com.znjc.device.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znjc.common.utils.DateUtils;
import com.znjc.device.domain.DeviceType;
import com.znjc.device.domain.DeviceTypeSerialRef;
import com.znjc.device.domain.IotDataCheck;
import com.znjc.device.domain.IotSerial;
import com.znjc.device.mapper.DeviceTypeMapper;
import com.znjc.device.service.IDeviceTypeSerialRefService;
import com.znjc.device.service.IDeviceTypeService;
import com.znjc.device.service.IIotDataCheckService;
import com.znjc.device.service.IIotSerialService;
import com.znjc.device.websocket.WebSocketUsers;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author zengpc
 * @date 2023-12-04
 */
@Service
public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceType> implements IDeviceTypeService {

    @Resource
    IDeviceTypeSerialRefService deviceTypeSerialRefService;
    @Resource
    private IIotSerialService iotSerialService;
    @Resource
    private IIotDataCheckService iotDataCheckService;
    @Override
    public List<DeviceType> getDeviceTypes(Long serialId) {
        List<Long> typeIds = deviceTypeSerialRefService.getIdList(serialId,1);
        if(CollectionUtils.isEmpty(typeIds)){
            return null;
        }
        LambdaQueryWrapper<DeviceType> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DeviceType::getId,serialId);
        return this.list(wrapper);
    }

    @Override
    public void editGather(DeviceType deviceType,String status) {
        JSONObject json = new JSONObject();
        json.put("openFlag", status);
        json.put("typeId", deviceType.getId());
        if("0".equals(status)){
            json.put("cron", deviceType.getGatherTime());
            IotSerial serial = iotSerialService.getSerialByTypeId(deviceType.getId());
            if(null != serial){
                json.put("serial", serial);
                //串口下的校验
                List<IotDataCheck> dataChecks = iotDataCheckService.getIotDataCheckListBySerialId(serial.getId());
                if(com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(dataChecks)){
                    throw new RuntimeException("该类型绑定的串口,无校验信息，无法采集数据!");
                }else{
                    json.put("dataChecks", dataChecks);
                }
            }else{
                throw new RuntimeException("该类型未绑定串口,无法采集数据!");
            }
        }
        WebSocketUsers.sendMessageToUserByText(deviceType.getDeptId() + "", json.toJSONString());
    }


}
